@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion

:: 云法务系统后端启动脚本 (Windows版本)
:: Author: CloudLegal Team
:: Date: 2024-01-01

:: 项目配置
set PROJECT_NAME=cloud-legal-backend
set JAR_NAME=cloud-legal-backend-1.0.0.jar
set MAIN_CLASS=com.cloudlegal.CloudLegalApplication
set JVM_OPTS=-Xms512m -Xmx1024m -XX:+UseG1GC
set PROFILES_ACTIVE=dev
set SERVER_PORT=8080

:: 日志配置
set LOG_DIR=logs
set LOG_FILE=%LOG_DIR%\application.log
set PID_FILE=%PROJECT_NAME%.pid

:: 创建日志目录
if not exist "%LOG_DIR%" mkdir "%LOG_DIR%"

:: 函数：打印消息
:print_message
echo [%date% %time%] %~2
goto :eof

:: 函数：检查Java环境
:check_java
if "%JAVA_HOME%"=="" (
    call :print_message INFO "JAVA_HOME未设置，尝试使用系统Java..."
    set JAVA_CMD=java
) else (
    set JAVA_CMD="%JAVA_HOME%\bin\java"
)

%JAVA_CMD% -version >nul 2>&1
if errorlevel 1 (
    call :print_message ERROR "错误：未找到Java环境，请安装JDK 17或更高版本"
    pause
    exit /b 1
)

:: 检查Java版本
for /f "tokens=3" %%g in ('%JAVA_CMD% -version 2^>^&1 ^| findstr /i "version"') do (
    set JAVA_VERSION=%%g
    set JAVA_VERSION=!JAVA_VERSION:"=!
    for /f "delims=." %%a in ("!JAVA_VERSION!") do set JAVA_MAJOR=%%a
)

if !JAVA_MAJOR! LSS 17 (
    call :print_message ERROR "错误：Java版本过低，需要JDK 17或更高版本"
    pause
    exit /b 1
)

call :print_message INFO "Java环境检查通过"
goto :eof

:: 函数：检查端口是否被占用
:check_port
netstat -an | findstr ":%SERVER_PORT%" | findstr "LISTENING" >nul
if not errorlevel 1 (
    call :print_message WARN "警告：端口 %SERVER_PORT% 已被占用"
    set /p continue="是否继续启动？(y/n): "
    if /i not "!continue!"=="y" (
        call :print_message INFO "启动已取消"
        pause
        exit /b 0
    )
)
goto :eof

:: 函数：检查进程是否运行
:is_running
if exist "%PID_FILE%" (
    set /p PID=<"%PID_FILE%"
    tasklist /FI "PID eq !PID!" 2>nul | findstr "!PID!" >nul
    if not errorlevel 1 (
        exit /b 0
    ) else (
        del "%PID_FILE%" >nul 2>&1
        exit /b 1
    )
)
exit /b 1

:: 函数：启动应用
:start_app
call :print_message INFO "正在启动 %PROJECT_NAME%..."

:: 检查是否已经运行
call :is_running
if not errorlevel 1 (
    call :print_message WARN "%PROJECT_NAME% 已经在运行中"
    goto :eof
)

:: 检查JAR文件是否存在
if not exist "target\%JAR_NAME%" (
    call :print_message INFO "JAR文件不存在，正在编译..."
    call mvn clean package -DskipTests
    if errorlevel 1 (
        call :print_message ERROR "编译失败"
        pause
        exit /b 1
    )
)

:: 启动应用
start /b %JAVA_CMD% %JVM_OPTS% ^
    -Dspring.profiles.active=%PROFILES_ACTIVE% ^
    -Dserver.port=%SERVER_PORT% ^
    -jar target\%JAR_NAME% ^
    > "%LOG_FILE%" 2>&1

:: 获取进程ID并保存
timeout /t 2 >nul
for /f "tokens=2" %%i in ('tasklist /FI "IMAGENAME eq java.exe" /FO CSV ^| findstr "%JAR_NAME%"') do (
    set PID=%%i
    set PID=!PID:"=!
)

if defined PID (
    echo !PID! > "%PID_FILE%"
)

:: 等待启动
call :print_message INFO "等待应用启动..."
timeout /t 5 >nul

:: 检查是否启动成功
call :is_running
if not errorlevel 1 (
    set /p PID=<"%PID_FILE%"
    call :print_message INFO "%PROJECT_NAME% 启动成功！"
    call :print_message INFO "PID: !PID!"
    call :print_message INFO "端口: %SERVER_PORT%"
    call :print_message INFO "接口文档: http://localhost:%SERVER_PORT%/api/doc.html"
    call :print_message INFO "日志文件: %LOG_FILE%"
) else (
    call :print_message ERROR "%PROJECT_NAME% 启动失败，请检查日志文件：%LOG_FILE%"
    pause
    exit /b 1
)
goto :eof

:: 函数：停止应用
:stop_app
call :print_message INFO "正在停止 %PROJECT_NAME%..."

call :is_running
if errorlevel 1 (
    call :print_message WARN "%PROJECT_NAME% 未运行"
    goto :eof
)

set /p PID=<"%PID_FILE%"
taskkill /PID !PID! /F >nul 2>&1

:: 等待进程结束
set count=0
:wait_stop
tasklist /FI "PID eq !PID!" 2>nul | findstr "!PID!" >nul
if not errorlevel 1 (
    set /a count+=1
    if !count! GTR 30 (
        call :print_message WARN "强制停止进程..."
        taskkill /PID !PID! /F >nul 2>&1
        goto :stop_done
    )
    timeout /t 1 >nul
    goto :wait_stop
)

:stop_done
del "%PID_FILE%" >nul 2>&1
call :print_message INFO "%PROJECT_NAME% 已停止"
goto :eof

:: 函数：重启应用
:restart_app
call :stop_app
timeout /t 2 >nul
call :start_app
goto :eof

:: 函数：查看状态
:status_app
call :is_running
if not errorlevel 1 (
    set /p PID=<"%PID_FILE%"
    call :print_message INFO "%PROJECT_NAME% 正在运行 (PID: !PID!)"
    call :print_message INFO "端口: %SERVER_PORT%"
    call :print_message INFO "接口文档: http://localhost:%SERVER_PORT%/api/doc.html"
) else (
    call :print_message WARN "%PROJECT_NAME% 未运行"
)
goto :eof

:: 函数：查看日志
:show_log
if exist "%LOG_FILE%" (
    type "%LOG_FILE%"
    echo.
    echo 按任意键查看实时日志...
    pause >nul
    powershell -Command "Get-Content '%LOG_FILE%' -Wait"
) else (
    call :print_message WARN "日志文件不存在：%LOG_FILE%"
)
goto :eof

:: 函数：显示帮助信息
:show_help
echo 用法: %0 {start^|stop^|restart^|status^|log^|help}
echo.
echo 命令说明：
echo   start   - 启动应用
echo   stop    - 停止应用
echo   restart - 重启应用
echo   status  - 查看运行状态
echo   log     - 查看实时日志
echo   help    - 显示帮助信息
echo.
echo 示例：
echo   %0 start    # 启动应用
echo   %0 status   # 查看状态
echo   %0 log      # 查看日志
goto :eof

:: 主程序
:main
if "%1"=="" (
    call :show_help
    pause
    exit /b 1
)

:: 检查Java环境
call :check_java

:: 根据参数执行相应操作
if /i "%1"=="start" (
    call :check_port
    call :start_app
) else if /i "%1"=="stop" (
    call :stop_app
) else if /i "%1"=="restart" (
    call :restart_app
) else if /i "%1"=="status" (
    call :status_app
) else if /i "%1"=="log" (
    call :show_log
) else if /i "%1"=="help" (
    call :show_help
) else (
    call :print_message ERROR "未知命令: %1"
    call :show_help
    pause
    exit /b 1
)

if not "%1"=="log" pause
goto :eof

:: 调用主程序
call :main %*
